<?php
namespace app\common\model;
use think\Model;
use think\facade\Db;

class Table extends Model
{
    /**
     * 关联权限
     * @return \think\model\relation\BelongsTo
     */
    public function fields()
    {
        return $this->hasMany(TableField::class, 'table_id', 'id');
    }

    /**
     * 更新表字段
     * @param $table_id
     */
    static function update_field($table_id)
    {
        // 启动事务
        Db::startTrans();
        try {
            $table_name = self::where('id',$table_id)->value('table');
            $sql = 'SHOW FULL COLUMNS FROM `hq_'.$table_name.'`';
            $tables_in_db = Db::query($sql);
            foreach ($tables_in_db as $k=>$t){
                //查费
                $type = explode('(', $t['Type']);
                $data['type'] = $type[0];
                $length_type = preg_replace("#^.*?\((.*?)\).*?$#us", "$1", $t['Type']);
                //
                $length = explode(',',$length_type);
                $data['length'] = $length[0];
                if(count($length) == 2){
                    $data['point'] = $length[1];
                }
                $data['table_id'] = $table_id;
                $data['field'] = $t['Field'];
                $data['collation'] = $t['Collation'];
                $data['null'] = $t['Null'];
                $data['key'] = $t['Key'];
                $data['default'] = $t['Default'];
                $data['extra'] = $t['Extra'];
                $data['privileges'] = $t['Privileges'];
                $data['comment'] = $t['Comment'];
                //查询是否存在
                $is_data = TableField::where(['table_id'=>$table_id,'field'=>$t['Field']])->find();
                if(empty($is_data)){
                    $result = TableField::create($data);
                }else{
                    $result = TableField::update($data,['id'=>$is_data['id']]);
                }
                if($result == false){
                    Db::rollback();
                    return false;
                }
            }
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

}